package com.rams.jhms.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.rams.jhms.Config;
import com.rams.jhms.logging.BaseLogger;

public class DerbyConnectionHelper {
	private static Connection conn = null;
	private static String connectionURL = "jdbc:derby://localhost:1527/data;user=jhms;password=jhms;";

	static {
		new DerbyConnectionHelper();
	}
	
	public DerbyConnectionHelper() {
		try {
			initDriver();
		} catch (ClassNotFoundException e) {
			BaseLogger.debug("DAO Connection Helper", e);
		} catch (SQLException e) {
			BaseLogger.debug("DAO Connection Helper", e);
		}
	}
	
	private static void initDriver() throws ClassNotFoundException, SQLException {
		if (Config.dbEmbeded) {
			/* code for compiled application for use embeded derby db */
			/*
			Class.forName("org.apache.derby.jdbc.EmbeddedDataSource").newInstance();
			EmbeddedSimpleDataSource ds = new EmbeddedSimpleDataSource(); 
			ds.setDatabaseName(Config.dbName);
			ds.setUser(Config.dbUserName);
			ds.setPassword(Config.dbUserPwd);
			conn = ds.getConnection();
			*/
		} else {
			/* code for developers for use derby server */
			try {
			conn = DriverManager.getConnection(connectionURL);
			} catch (Exception e) {
				BaseLogger.debug("DAO Connection Helper", e);
			}
		}
	}
	
	public static Connection getConnection() {
		return conn;
	}

    public static void close (Connection conn) {
    	
    }

    public static void close (ResultSet resultSet) {
        if(resultSet != null)
            try {
                resultSet.close();
            } catch (SQLException e) {
            	BaseLogger.debug("DAO Connection Helper", e);
            }
    }

    public static void close(Statement statement) {
        if(statement != null)
            try {
                statement.close();
            } catch (SQLException e) {
            	BaseLogger.debug("DAO Connection Helper", e);
            }

    }

}

// TODO: !!!!need to refactoring this class!!!!